package com.hs.chd.action.standword;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.model.HsAccount;
import com.hs.chd.model.SchdFileinfo;
import com.hs.chd.model.SchdImpfileinfo;
import com.hs.chd.model.SchdStandword;
import com.hs.chd.service.IDataService;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.imp.ExcelImportUtil;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
@Controller   
public class StandwordDataController  extends BaseAction {
    private static final Logger logger = Logger.getLogger(StandwordDataController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	
	 /**
	  * 标准数据管理框架页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/standard/standdataframe.do", method = RequestMethod.GET)   
    public ModelAndView standdataframe(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
        
		 return new ModelAndView("app/standard/standlistframe",modelMap);
		 
	 } 
	 /**
	  * 标准数据列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/standard/standardlist.do")   
     public ModelAndView standardlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 PageParam pageParam = new  PageParam(request,"standard/standardlist.do");
		 PageUtil pageUtil = null;
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum");
		 String datatype = "1";
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("a.rightname").append(" asc");
		    	orderName = "a.rightname";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 pageParam.getConditionMap().put("orderName", orderName);
		 pageParam.getConditionMap().put("orderNum", orderNum);
		 StringBuffer searchBuffer = new StringBuffer(" select a from SchdStandword a where 1=1   ");
			String rightname = request.getParameter("rightname");  
 			//String periodicalname = request.getParameter("periodicalname"); 
			request.setAttribute("rightname", rightname==null?rightname:rightname.trim());
 			//request.setAttribute("periodicalname", periodicalname);
			if(StringUtils.isNotBlank(rightname)){
				String temp = rightname.trim();
				searchBuffer.append(" and (a.rightname like '%").append(temp).append("%' ");
				searchBuffer.append(" or a.othername like '%").append(temp).append("%') ");
				pageParam.getConditionMap().put("rightname", temp); 
			}  
//			if(StringUtils.isNotBlank(author)){
//				pageParam.getConditionMap().put("author", author.trim());
//				searchBuffer.append(" and (a.author like '%"+author.trim()+"%') "); 
//			}
//			 
			searchBuffer.append(orderByStr);
			//Map data = new HashMap();
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = dataService.getPageList(pageParam);
			modelMap.put("dataList", pageUtil);     
		  return new ModelAndView("app/standard/standardlist",modelMap);
		 
	 }
	 /**
	  * 标准数据导入页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/standard/standimport.do", method = RequestMethod.GET)   
     public ModelAndView standimport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/standard/standimportview",modelMap);
		 
	 }
	
	 /**
	  * 标准数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/executestandardimport.do")   
     public void executestandardimport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("importfile");   
		 String fileName = multipartFile.getOriginalFilename(); 
		 String webRoot = SystemUtil.getWebappRoot().toString();
		 webRoot = webRoot.replace("\\", "/") + "/temp"; 
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
		 File rootDir = new File(webRoot); 
		 if (!rootDir.exists()) {
			rootDir.mkdirs(); 
		 }
		 File file = new File(webRoot + sep + fileName);
		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
		 bf.write(multipartFile.getBytes());
		 bf.close();
		 logger.debug("文件"+fileName+"上传成功!");
		 
		 HsAccount acc = this.getCurrentuser(request);
 		 String username = acc==null?"":acc.getUserinfo()==null?"":acc.getUserinfo().getUsername();
		 Map datamap  = this.checkAndImpData(file,username);
		 String info = (String)datamap.get("info");
		 List datalist = (List)datamap.get("datalist");
		 logger.debug("info:" + info);
		 logger.debug("datalist:" + datalist);
		 if(StringUtils.isNotEmpty(info)){
			 response.getWriter().write("错误信息:\n"+info);
		 }else{
			 this.dataService.saveOrUpdateAll(datalist);
			 response.getWriter().write("共导入标准数据【"+datalist.size()+"】条.");
		 }
		  
	    // return new ModelAndView("app/data/magaimportview",modelMap);
 		 
	 }
	 /**
	  * 标准数据导入前检查
	  * @param datafile
	  * @param impuser
	  * @return
	  */
	 private Map checkAndImpData(File datafile,String impuser){
		 Map datamap = new HashMap();
		 StringBuffer buffer = new StringBuffer(""); 
		 List datalist = new ArrayList();
		 ExcelImportUtil inst = ExcelImportUtil.getInstance(datafile);
		 HSSFWorkbook workbook = null;
		 try {
				workbook = inst.readFile();
				int total = workbook.getNumberOfSheets(); //获取sheet个数      
		        int start = 0;
		        int end = 0 ;   
		        //获取sheet个数
		        Map doublemap = new HashMap();
				for(int i = 0 ; i < total ; i ++){  
		            HSSFSheet sheet = workbook.getSheetAt(i);// 按索引获取sheet引用   
		            start = sheet.getFirstRowNum();  //sheet起始行索引      
		            end = sheet.getLastRowNum();//sheet起结束行索引      
		            int counter = 1;      
		            HSSFRow row = null ; 
		            HSSFCell tcmname = null ; 
		        	HSSFCell tcmothername = null ;  
		        	
		            while(counter <= end){      
		            	SchdStandword std = null;
		                 row =  sheet.getRow(counter);//获取第N行表格数据     
		                 if(row != null){
		                	 counter ++ ;
		                	 tcmname = row.getCell(1);//获取指定列单元格            
		                	 tcmothername = row.getCell(2);    
		  		        	 String tcmstr = getCell(tcmname);
			                 String tcmothernamestr = getCell(tcmothername);
//			                 if(StringUtils.isNotEmpty(tcmstr)){
//			                	 String obj = (String)doublemap.get(tcmstr);
//			                	 if(null == obj){
//				                	 doublemap.put(tcmstr, tcmstr); 
//			                	 }else{
//			                		 buffer.append("第【"+counter +"】行正名存在重复数据.\n");
//			                	 }
//			                 } 
			                 if(StringUtils.isNotEmpty(tcmothernamestr)){
			                	 String obj = (String)doublemap.get(tcmothernamestr);
			                	 if(null == obj){
				                	 doublemap.put(tcmothernamestr, tcmothernamestr); 
			                	 }else{
			                		 buffer.append("第【"+counter +"】行异名存在重复数据.\n");
			                	 }
			                 } 
			                 
			                 if(StringUtils.isEmpty(tcmstr)){
			                	 buffer.append("第【"+counter +"】行数据错误，病名不能为空.\n");
			                	 continue;
			                 }
		  		        	 StringBuffer countsql = new StringBuffer();
			                 countsql.append("select id from CHD_STANDWORD ");
			                 countsql.append(" where RIGHTNAME='");
			                 countsql.append(tcmstr==null?null:tcmstr.trim().replaceAll("'", "''")); 
			                 countsql.append("'");
			                 if(StringUtils.isNotEmpty(tcmothernamestr)){
			                	 countsql.append(" and OTHERNAME='" + tcmothernamestr.trim() + "'");
			                 } 
			                 
							 List accList = DBMgr.getDbUtilInst().queryList(countsql.toString(),null);  
							 int acclen = accList.size();
							 if(acclen >0){ 
								 buffer.append("第【"+counter +"】行数据重复.\n");
								 continue;
							 }else{
								 std = new SchdStandword();  
				                 std.setImpuser(impuser);
				                 std.setRightname(tcmstr);
				                 std.setOthername(tcmothernamestr);
				                 std.setImpdate(TimeUtil.getCurrentDate());
				                 std.setIsdelete(new Long(0)); 
				                 datalist.add(std);
							 }
				                 
		                 }
		                  
		            } 
				}
			} catch (FileNotFoundException e) { 
				logger.debug("文件不存在:" + e.getMessage());
				buffer.append("数据文件读取异常，请重试.\n"+e.getMessage());
			} catch (IOException e) { 
				logger.debug("读取文件异常:" + e.getMessage());
				buffer.append("数据文件读取异常，请重试.\n"+e.getMessage());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				buffer.append("数据文件读取异常，请重试.\n"+e.getMessage());
			}  
		 datamap.put("info", buffer.toString());
		 datamap.put("datalist", datalist);
 		 return datamap;
	 }
	 /**
	  * 标准数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/standard/standardexport.do")   
	public ModelAndView standardexport(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String path = this.exportStdData("");
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
		 
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/vnd.ms-excel":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
     }  catch  (IOException ex) {
         ex.printStackTrace();
     }
		return null;  
	} 
	
 
	public String getCell(HSSFCell cell){
		if(cell==null)return "";
		switch(cell.getCellType()){
			case HSSFCell.CELL_TYPE_NUMERIC:
				return (long)cell.getNumericCellValue() + "";
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			case	HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case HSSFCell.CELL_TYPE_ERROR:
	    	    return cell.getErrorCellValue() + "";
	    	default:
	    		return "";
		}
	}
	
	private String null2str(String content){
		if(null == content || "null".equalsIgnoreCase(content)){
			return "";
		}
		return content;
	}
	/**
	 * 生成标准数据导出文件
	 * @return 生成的文件的路径
	 */
	public String exportStdData(String rid){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("stddata"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("序号"); 
				 row.createCell(1).setCellValue("病名"); 
				 row.createCell(2).setCellValue("异名"); 
				 CellStyle cs=wb.createCellStyle(); 
				 List accList = null;
				 if("".equals(rid)){
					 accList = DBMgr.getDbUtilInst().queryList("select * from CHD_STANDWORD order by id",null);
				 }else{
					 accList = DBMgr.getDbUtilInst().queryList("select * from CHD_STANDWORD where id=? order by id",new Object[]{rid});
				 }
				 
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						Object obj  = data.get("id");
						if(obj instanceof Long){
							System.out.println("*****************");
						}else if(obj instanceof Integer){
							System.out.println("&&&&&&&&&&&&&");
						}else if(obj instanceof Double){
							System.out.println("################");
						}
						onerow.createCell(0).setCellValue(String.valueOf(data.get("id"))); 
						onerow.createCell(1).setCellValue((String)data.get("RIGHTNAME")); 
						onerow.createCell(2).setCellValue((String)data.get("OTHERNAME")); 
						 
				 }	
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "病名标准数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
	 private static String cutStr(String str){
		 if(str.lastIndexOf(',') != -1){
			 str = str.substring(0, str.length()-1);
		 }
		 return str;
	 }
}
